package com.server.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @Description: TODO 日志统一切面
 * @Author: mis_wu
 * @Date: 2022/7/27
 **/
@Component
@Aspect
public class CloudServerLogAspect {

    private static final Logger log = LoggerFactory.getLogger(CloudServerLogAspect.class);

    @Pointcut("execution(public * com.server.controller.*.*(..))")
    public void serverLog(){}

    @Before("serverLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        Object target = joinPoint.getTarget();
        log.info("server app log joinPoint getTarget:{}",target);
        List<Object> paramList = new ArrayList<>();
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String remoteAdd = request.getRemoteAddr();
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()){
            String param = names.nextElement();
            String parameter = request.getParameter(param);
            paramList.add(parameter);
        }
        log.info("请求地址:{},请求方法:{},请求ip:{},请求参数:{}",url,method,remoteAdd,paramList);
    }

    /**
     * 处理完请求返回值
     * @param response res
     */
    @AfterReturning(returning = "response",pointcut = "serverLog()")
    public void doAfterReturning(Object response) throws Throwable {
        log.info("请求返回值:{}",response);
    }

}
